<?php
/*
 * redis 相关的数据操作
 */
namespace app\api\controller;
use app\BaseController;
use think\facade\Cache;
use Redis;
use think\facade\Db;

class RedisData extends BaseController{
    public $userId = 10;
    /*
     * 商品的访问人数存入redis
     */
    public function goodsNum(){
        $goodsId = rand(1,10);
        $res = Cache::inc('goods_num'.$goodsId);
        if($res){
            echo "数据存入redis里面了";
            exit();
        }else{
            echo "数据存入失败";
            exit();
        }
    }
    /*
     * 查看
     */
    public function cart(){
        $userId = $this->userId;
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        $data = $redis->hGetAll("mall_cart_".$userId);
        echo "<pre>";
        print_r($data);
        echo "</pre>";
        exit;
    }
    /*
     * 购物车的操作redis
     */
    public function cartAdd(){
        $id = input('param.id',1,'intval');
        $num = input('param.num',1,'intval');
        $userId = $this->userId;
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        $goodsData = Db::table('shop_goods')->where('id', $id)->find();
        $data['goods_id'] = $goodsData['id'];
        $data['title'] = $goodsData['good_title'];
        $data['thumb'] = $goodsData['thumb'];
        $data['num'] = $num;
        $get = $redis->hGet("mall_cart_".$userId,$id);
        if($get){
              $get = json_decode($get,true);
              $data['num'] = $get['num']+$data['num'];
        }
        $res = $redis->hSet("mall_cart_".$userId,$id,json_encode($data));
        if($res === false){
            echo "数据加入失败";
        }else{
            echo "数据加入成功";
        }
    }


}